var config = require('../../common/config');
var request = require('request');
var utils = require('../../common').utils;
var _ = require('underscore');

var reqTemplate = config.reqTemplate;
var logger = config.logger('app');

var orderTypeEnum = {
    "RENT_WITH_DRIVER": "包车",
    "RENT_NO_DRIVER": "包车",
    "TRAVEL_RENT": "旅游",
    "GO_AIRPORT": "送机",
    "OFF_AIRPORT": "接机",
    "PIECE":"拼车"
};

var orderStatusEnum = {
    "DEFINE": "已下单",
    "PAID": "已支付",
    "ENSURE": "已出车",
    "FINISH": "已完成",
    "CANCEL": "已取消"
}

exports.login = function (req, res) {
    var option = new reqTemplate("user/login");
    option.form = _.extend(option.form, req.body);

    request(option, function (err, response) {
        if (err) {
            logger.error(err.trace);
            res.send(response || err);
        }
        else {
            res.send(eval("(" + response.body + ")"));
        }
    });
};

exports.register = function (req, res) {
    var option = new reqTemplate("user");
    option.form = _.extend(option.form, req.body);
    option.form.role = "user";
    option.form.vercode = (Math.random() + "").substring(2, 8);
    //option.form.emailVerified = true;

    request(option, function (err, response) {
        if (err) {
            logger.error(err.trace);
            res.send(response || err);
        }
        else {
            res.send(eval("(" + response.body + ")"));
        }
    });
};

exports.modifyAccount = function(req,res){
    var user = utils.generateCookie(req.headers.cookie);
    var option = new reqTemplate("user/"+user.userId,"PUT");
    option.form = _.extend(option.form, req.body);
    option.headers.authorization = user.uuId;
    request(option, function (err, response) {
        if (err) {
            logger.error(err.trace);
            res.send(response || err);

        } else {
            res.send(eval("(" + response.body + ")"));
        }
    });
};

exports.resetPassword = function (req, res) {
    var option = new reqTemplate("user/resetRequest");
    option.form = _.extend(option.form, req.query);

    request(option, function (err, response) {
        if (err) {
            logger.error(err.trace);
            res.send(response || err);
        } else {
            if (response.body.match("成功")) {
                res.send("success");
            } else {
                res.send("fail");
            }
        }
    });
};

exports.userCenterPage = function (req, res) {
    var user = utils.generateCookie(req.headers.cookie);

    if (!user || !user.userId) {
        res.redirect("/user/login");
        return;
    }

    var option = new reqTemplate("user/" + user.userId, "GET");
    option.headers.authorization = user.uuId;
    request(option, function (err, response) {
        if (err) {
            logger.error(err.trace);
            res.send(response || err);
        } else {

            option = new reqTemplate("order_list", "GET");
            option.form.filter = {
                where: {user_id: user.userId},
                order: ["createdAt DESC"],
                limit: 4
            };

            request(option, function (err, orderRes) {
                if (err) {
                    logger.error(err.trace);
                    res.send(response || err);
                } else {
                    var obj = eval("(" + response.body + ")");
                    var order = eval("(" + orderRes.body + ")");
                    if (!obj.nick_name) {
                        obj.nick_name = obj.username;
                    }
                    if(!obj.balance) {
                        obj.balance = 0;
                    }

                    order.forEach(function (e) {
                        e.createdAt = new Date(e.createdAt).valueOf();
                        e.order_type = orderTypeEnum[e.order_type];
                        e.status = orderStatusEnum[e.status];
                        if (!e.driver_info) {
                            if (e.order_type == "RENT_NO_DRIVER") {
                                e.driver_info = {
                                    name: "无司机",
                                    tel: "/"
                                }
                            } else {
                                e.driver_info = {
                                    name: "待定",
                                    tel: "待定"
                                }
                            }
                        }
                        if (!e.car_info) {
                            e.car_info = {
                                car_type: "待定",
                                car_number: ""
                            }
                        }
                        if (!e.end_time) {
                            e.end_time = "/";
                        } else {
                            e.end_time = new Date(e.end_time).Format('yyyy-MM-dd hh:mm');
                        }
                        if(!e.car_info) {
                            e.car_info = {
                                car_type : "",
                                car_number : ""
                            }
                        }
                        if(!e.car_info.car_type) {
                            e.car_info.car_type = "";
                            e.car_info.car_number = "";
                        }
                        e.start_time = new Date(e.start_time).Format('yyyy-MM-dd hh:mm');
                    });
                    var renderObj = {user: obj, order: order, no_more: false};
                    if (order.length < 4) {
                        renderObj.no_more = true;
                    }
                    res.render("userCenter.hbs", renderObj);
                }
            });
        }
    });
};

exports.findOrderList = function (req, res) {
    var user = utils.generateCookie(req.headers.cookie);

    if (!user || !user.userId) {
        res.redirect("/user/login");
        return;
    }

    var option = new reqTemplate("order_list", "GET");
    option.form.filter = {
        where: {user_id: user.userId},
        order: ["createdAt DESC"],
        limit: 4,
        skip : (req.body.page-1) * 4
    };

    request(option, function (err, orderRes) {
        if (err) {
            logger.error(err.trace);
            res.send(response || err);
        } else {
            var order = eval("(" + orderRes.body + ")");
            order.forEach(function (e) {
                e.createdAt = new Date(e.createdAt).valueOf();
                e.order_type = orderTypeEnum[e.order_type];
                e.status = orderStatusEnum[e.status];
                if (!e.driver_info) {
                    if (e.order_type == "RENT_NO_DRIVER") {
                        e.driver_info = {
                            name: "无司机",
                            tel: "/"
                        }
                    } else {
                        e.driver_info = {
                            name: "待定",
                            tel: "待定"
                        }
                    }
                }
                if (!e.car_info) {
                    e.car_info = {
                        car_type: "待定",
                        car_number: ""
                    }
                }
                if (!e.end_time) {
                    e.end_time = "/";
                } else {
                    e.end_time = new Date(e.end_time).Format('yyyy-MM-dd hh:mm');
                }
                if(!e.car_info) {
                    e.car_info = {
                        car_type : "",
                        car_number : ""
                    }
                }
                if(!e.car_info.car_type) {
                    e.car_info.car_type = "";
                    e.car_info.car_number = "";
                }
                e.start_time = new Date(e.start_time).Format('yyyy-MM-dd hh:mm');
            });
            res.send(order);
        }
    });
};

exports.uploadFile = function(req,res) {
    console.log(req.body);
    res.send("success");
}